import React, {Component} from 'react';
import {View, StyleSheet,} from 'react-native';
import Svg, {G, Path, Rect, Defs, ClipPath, Polyline, Image} from 'react-native-svg';


/**
 * 大体实现刮刮乐
 */
export default class ScratchCard extends Component {

  state = {
    strokePath: undefined
  }

  /**
   * 笔画数组
   * @type {Array}
   */
  strokeArray = [[]]

  /**
   * 是否采集坐标（用于限制坐标采集频率，优化性能）
   * @type {Boolean}
   */
  strokeAllow = true

  /**
   * 绘制图案
   * @return {void}
   */
  strokeCanvas = () => {
    this.strokeAstrict(() => {


      this.setState({
        strokePath: this.strokeArray
      }, () => console.log('this.strokeArray', this.strokeArray));
    });
  }

  /**
   * 限制坐标采集频率
   * @param  {Function} strokeMethod 绘图函数
   * @return {void}
   */
  strokeAstrict = strokeMethod => {
    if (this.strokeAllow) {
      this.strokeAllow = false;
      const timer = setTimeout(() => {
        this.strokeAllow = true;
        clearTimeout(timer);
      }, 50);

      strokeMethod()
    }
  }

  /**
   * 手指滑动事件
   * @param  {Object} event 事件对象
   * @return {void}
   */
  touchMove = event => {
    const {locationX, locationY} = event.nativeEvent;
    this.strokeArray[this.strokeArray.length - 1].push({
      x: locationX,
      y: locationY,
    });
    this.strokeCanvas();
  }

  /**
   * 手指离开事件
   * @return {void}
   */
  touchEnd = (event) => {
    this.strokeArray.push([]);
  }


  /**
   * 清除画布
   * @return {void}
   */
  clear = () => {
    this.setState({
      strokePath: [[]],
    });

    this.strokeArray = [[]];
  }

  render() {
    const {strokePath} = this.state;
    const {width = 300, height = 400, endHref} = this.props;

    return (
      <View style={[styles.box, {width, height}]} ref={ref => this.viewRef = ref}>
        <View
          onStartShouldSetResponder={() => true}
          onResponderMove={this.touchMove}
          onResponderRelease={this.touchEnd}
        >
          <Svg width={width} height={height} style={{backgroundColor:'#ccc'}}>
            {/*定义裁剪*/}
            <Defs>
              <ClipPath id={`clip`}>
                {
                  strokePath && strokePath.length > 0 && strokePath.map((sign, index) => {
                    let path = '';
                    sign.map(({x, y}, i) => {
                      path = path + `${x},${y} `
                    });
                    console.log('ClipPath',path);
                    return (
                      <Polyline
                        key={index}
                        points={path} stroke="red" strokeWidth={50}
                        fill="none"/>
                    )
                  })
                }
              </ClipPath>
            </Defs>
            <Image
              x={0}
              y={0}
              height={height}
              width={width}
              href={endHref}
              clipPath="url(#clip)"
            />


          </Svg>

        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  box: {
    backgroundColor: '#fff',
  }
})